package com.lyl.redis.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import com.lyl.redis.common.annotation.NoRepeatSubmit;
import com.lyl.redis.common.base.ConstantPool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Mr.Luo
 */
@Slf4j
@RestController
@RequestMapping("/redis")
public class RedisController {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/getId")
    public Long getId() {
        //判断redis中是否存在订单单号
        Boolean hasKey = redisTemplate.hasKey(ConstantPool.REDIS_KEY_ORDER_ID);
        if (Boolean.FALSE.equals(hasKey)) {
            Long date = Long.valueOf(DateUtil.format(new Date(), "yyyyMMddHHmmss"));
            redisTemplate.opsForValue().set(ConstantPool.REDIS_KEY_ORDER_ID, date, 60, TimeUnit.SECONDS);
            return date;
        }
        return redisTemplate.opsForValue().increment(ConstantPool.REDIS_KEY_ORDER_ID);
    }

    @GetMapping("/hello")
    @NoRepeatSubmit
    public String hello() {
        log.info("执行方法名: hello() ");
        return "hello,world";
    }

    @PostMapping("/hello2")
    @NoRepeatSubmit
    public String hello2(@RequestBody Map<String, Object> param) {
        log.info("方法名: hello2() , 参数值: param = [" + param + "]");
        redisTemplate.opsForValue().increment("method:hello2");
        ThreadUtil.safeSleep(2000);
        if (param.containsKey("sex")) {
            throw new RuntimeException("手动抛出异常");
        }
        return "hello,world by have params request";
    }

    @GetMapping("/hello3")
    @NoRepeatSubmit
    public String hello3(String name) {
        log.info("执行方法名: hello3() , name = " + name);
        return "hello,world";
    }
}
